<?php

namespace app\agent\controller;

use app\common\controller\Adminbase;
use app\job\SyncGoodsJob;
use app\model\AgentGoods;
use app\model\Goods as GoodsModel;
use app\model\GoodsCategory;
use app\model\GoodsSync;
use app\model\GoodsType;
use app\service\AgentService;
use think\Queue;

class GoodsAll extends Adminbase
{
    public function index()
    {
        $model = 'Goods';

        $agent = AgentService::getAgentInfo(UID);
        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $order = 'sort asc, id desc';
            $where = [];
            foreach ($map as $key => $item) {
                if ($item[0] == 'sort_type') {
                    $value = $item[2];
                    unset($map[$key]);
                    switch ($value) {
                        case 1:
                            $order = 'partners_subsidy_push asc, sort asc';
                            break;
                        case 2:
                            $order = 'partners_subsidy_push desc, sort asc';
                            break;
                        case 3:
                            $order = 'partners_subsidy_shop asc, sort asc';
                            break;
                        case 4:
                            $order = 'partners_subsidy_shop desc, sort asc';
                            break;
                        case 5:
                            $order = 'commission asc, sort asc';
                            break;
                        case 6:
                            $order = 'commission desc, sort asc';
                            break;
                    }
                }
                if ($item[0] == 'subsidy_type' && !empty($item[2])) {
                    unset($map[$key]);
                    switch ($item[2]) {
                        case "1":
                            $where[] = ['is_partners_subsidy', 'eq', 1];
                            break;
                        case "2":
                            $where[] = ['partners_subsidy_push', 'gt', 0];
                            break;
                        case "3":
                            $where[] = ['partners_subsidy_shop', 'gt', 0];
                            break;
                    }
                }
                if ($item[0] == 'add_type' && !empty($item[2])) {
                    unset($map[$key]);
                    $add_goods = AgentGoods::where('agent_id', $agent['id'])->column('goods_id');
                    if ($item[2] == 1) {
                        $where[] = ['id', 'not in', $add_goods];
                    } else {
                        $where[] = ['id', 'in', $add_goods];
                    }
                }
            }
            $query = GoodsModel::where($map);
            if ($where) {
                $query->where($where);
            }
            $count_query = clone $query;

            $list  = $query
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_push', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('partners_subsidy_shop', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order($order)
                ->select()->toArray();
            $total = $count_query->count();

            if ($list) {
                $goods_ids = array_column($list, 'id');
                $goods     = AgentGoods::where('goods_id', 'in', $goods_ids)->where('agent_id', $agent['id'])->column('goods_id');
                foreach ($list as &$item) {
                    $item['is_add'] = in_array($item['id'], $goods) ? 1 : 0;
                }
            }

            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $subsidy_type = [
            '1' => '全部补贴',
            '2' => '补贴推客',
            '3' => '补贴小店',
        ];
        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDelBtn(false)
            ->setDataUrl()
            ->setFormUrl('')
            ->addSearchItem('subsidy_type', 'select', '补贴计划', $subsidy_type)
            ->addSearchItem('add_type', 'select', '选品筛选', [1 => '未选品', 2 => '已选品'])
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('sale_price', 'between', '售价', [], 100)
            ->addSearchItem('commission', 'between', '佣金', [], 100)
            ->addSearchItem('sort_type', 'select', '排序', [1 => '按推客补贴升序', 2 => '按推客补贴倒序', 3 => '按小店补贴升序', 4 => '按小店补贴倒序', 5 => '按佣金升序', 6 => '按佣金倒序'])
            ->setLimit()
            ->setModel($model)
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('product_id', '商品ID', 158)
            ->addTableColumn('title', '标题', 520)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('sale_price', '销售价格', 125)
            ->addTableColumn('commission', '佣金', 125)
            ->addTableColumn('partners_subsidy_push', '补贴推客佣金', 125)
            ->addTableColumn('partners_subsidy_shop', '补贴小店佣金', 125)
            ->addTableOperation()
            ->setFieldSelfBtn([
                ['type' => 'confirm', 'title' => '选品', 'url' => url('add', ['agent_id' => $agent['id']]), 'class' => 'layui-btn-normal', 'msg' => '是否添加选品？', 'field' => 'is_add', 'value' => '0']
            ])
            ->returnForm();

        $this->assign('text', "补贴计划<br>补贴推客佣金：您团长下的推客，推广该商品后，【您团长】可以获得的补贴佣金<br>补贴小店佣金：若该商品属于您团长下所邀请的小店，任意推客推广该商品后，【您团长】可以获得的补贴佣金");
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function add()
    {
        $id       = input('id/d');
        $agent_id = input('agent_id/d');
        $res      = AgentGoods::create([
            'agent_id' => $agent_id,
            'goods_id' => $id,
        ]);
        if ($res) {
            return json(['code' => 1, 'msg' => '添加成功']);
        } else {
            return json(['code' => -1, 'msg' => '添加失败']);
        }
    }

}
